<template>
  <div class="note-editor-container">
    <div class="editor-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <el-input
          v-model="noteForm.title"
          placeholder="请输入笔记标题..."
          class="title-input"
          size="large"
        />
      </div>
      <div class="header-right">
        <el-button @click="saveNote" :loading="saving" type="primary">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
        <el-dropdown @command="handleCommand">
          <el-button>
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export">导出</el-dropdown-item>
              <el-dropdown-item command="share">分享</el-dropdown-item>
              <el-dropdown-item command="template">保存为模板</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="editor-toolbar">
      <div class="toolbar-left">
        <el-select v-model="noteForm.categoryId" placeholder="选择分类" style="width: 150px;">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
        <el-select
          v-model="noteForm.tags"
          multiple
          filterable
          allow-create
          placeholder="添加标签"
          style="width: 200px;"
        >
          <el-option
            v-for="tag in availableTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button-group>
          <el-button 
            :type="editorMode === 'edit' ? 'primary' : 'default'"
            @click="editorMode = 'edit'"
            size="small"
          >
            编辑
          </el-button>
          <el-button 
            :type="editorMode === 'preview' ? 'primary' : 'default'"
            @click="editorMode = 'preview'"
            size="small"
          >
            预览
          </el-button>
          <el-button 
            :type="editorMode === 'split' ? 'primary' : 'default'"
            @click="editorMode = 'split'"
            size="small"
          >
            分屏
          </el-button>
        </el-button-group>
      </div>
    </div>

    <div class="editor-body" :class="{ 'split-mode': editorMode === 'split' }">
      <!-- 编辑区域 -->
      <div v-show="editorMode === 'edit' || editorMode === 'split'" class="editor-panel">
        <div class="editor-tools">
          <el-button-group size="small">
            <el-button @click="insertText('**粗体**')" icon="Bold">粗体</el-button>
            <el-button @click="insertText('*斜体*')" icon="Italic">斜体</el-button>
            <el-button @click="insertText('~~删除线~~')" icon="Strikethrough">删除线</el-button>
          </el-button-group>
          <el-button-group size="small">
            <el-button @click="insertText('# ')" icon="Heading">标题</el-button>
            <el-button @click="insertText('- ')" icon="List">列表</el-button>
            <el-button @click="insertText('> ')" icon="ChatLineRound">引用</el-button>
          </el-button-group>
          <el-button-group size="small">
            <el-button @click="insertText('`代码`')" icon="Code">代码</el-button>
            <el-button @click="insertText('[链接](url)')" icon="Link">链接</el-button>
            <el-button @click="showImageDialog = true" icon="Picture">图片</el-button>
          </el-button-group>
          <el-button size="small" @click="showTableDialog = true" icon="Grid">表格</el-button>
        </div>
        <el-input
          ref="editorTextarea"
          v-model="noteForm.content"
          type="textarea"
          placeholder="开始写下你的想法..."
          class="editor-textarea"
          @keydown="handleKeydown"
        />
      </div>

      <!-- 预览区域 -->
      <div v-show="editorMode === 'preview' || editorMode === 'split'" class="preview-panel">
        <div class="preview-content" v-html="previewContent"></div>
      </div>
    </div>

    <!-- 插入图片对话框 -->
    <el-dialog v-model="showImageDialog" title="插入图片" width="500px">
      <el-tabs v-model="imageTabActive">
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将图片拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="图片链接" name="url">
          <el-form :model="imageForm" label-width="80px">
            <el-form-item label="图片URL">
              <el-input v-model="imageForm.url" placeholder="请输入图片链接" />
            </el-form-item>
            <el-form-item label="图片描述">
              <el-input v-model="imageForm.alt" placeholder="请输入图片描述" />
            </el-form-item>
          </el-form>
          <div style="text-align: right;">
            <el-button @click="showImageDialog = false">取消</el-button>
            <el-button type="primary" @click="insertImageUrl">插入</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 插入表格对话框 -->
    <el-dialog v-model="showTableDialog" title="插入表格" width="400px">
      <el-form :model="tableForm" label-width="80px">
        <el-form-item label="行数">
          <el-input-number v-model="tableForm.rows" :min="2" :max="10" />
        </el-form-item>
        <el-form-item label="列数">
          <el-input-number v-model="tableForm.cols" :min="2" :max="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTableDialog = false">取消</el-button>
        <el-button type="primary" @click="insertTable">插入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getNoteDetail,
  createNote,
  updateNote,
  getNoteCategories,
  getNoteTags,
  uploadNoteImage
} from '@/api/note'

const route = useRoute()
const router = useRouter()

// 响应式数据
const saving = ref(false)
const editorMode = ref('edit')
const showImageDialog = ref(false)
const showTableDialog = ref(false)
const imageTabActive = ref('upload')
const categories = ref([])
const availableTags = ref([])
const editorTextarea = ref()
const uploadUrl = ref('/api/upload/image')

// 表单数据
const noteForm = reactive({
  id: undefined,
  title: '',
  content: '',
  categoryId: undefined,
  tags: []
})

const imageForm = reactive({
  url: '',
  alt: ''
})

const tableForm = reactive({
  rows: 3,
  cols: 3
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

const previewContent = computed(() => {
  // 简单的Markdown渲染，实际项目中建议使用专业的Markdown解析器
  return noteForm.content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/~~(.*?)~~/g, '<del>$1</del>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/^- (.*$)/gim, '<li>$1</li>')
    .replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
    .replace(/\n/g, '<br>')
})

// 获取笔记分类
const loadCategories = async () => {
  try {
    const response = await getNoteCategories()
    if (response.code === 200) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取标签
const loadTags = async () => {
  try {
    const response = await getNoteTags()
    if (response.code === 200) {
      availableTags.value = response.data
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 获取笔记详情
const loadNoteDetail = async () => {
  if (!isEdit.value) return
  
  try {
    const response = await getNoteDetail(route.params.id)
    if (response.code === 200) {
      Object.assign(noteForm, response.data)
    }
  } catch (error) {
    console.error('获取笔记详情失败:', error)
    ElMessage.error('获取笔记详情失败')
  }
}

// 保存笔记
const saveNote = async () => {
  if (!noteForm.title.trim()) {
    ElMessage.warning('请输入笔记标题')
    return
  }
  
  saving.value = true
  try {
    if (isEdit.value) {
      await updateNote(noteForm.id, noteForm)
      ElMessage.success('更新成功')
    } else {
      const response = await createNote(noteForm)
      if (response.code === 200) {
        ElMessage.success('保存成功')
        router.replace(`/note/${response.data.id}/edit`)
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 插入文本
const insertText = (text) => {
  const textarea = editorTextarea.value?.textarea
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const content = noteForm.content
  
  noteForm.content = content.substring(0, start) + text + content.substring(end)
  
  nextTick(() => {
    textarea.focus()
    textarea.setSelectionRange(start + text.length, start + text.length)
  })
}

// 处理键盘事件
const handleKeydown = (event) => {
  // Ctrl+S 保存
  if (event.ctrlKey && event.key === 's') {
    event.preventDefault()
    saveNote()
  }
  // Tab 键插入缩进
  if (event.key === 'Tab') {
    event.preventDefault()
    insertText('  ')
  }
}

// 图片上传成功
const handleImageSuccess = (response) => {
  if (response.code === 200) {
    const imageMarkdown = `![图片](${response.data.url})`
    insertText(imageMarkdown)
    showImageDialog.value = false
    ElMessage.success('图片上传成功')
  }
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 插入图片链接
const insertImageUrl = () => {
  if (!imageForm.url) {
    ElMessage.warning('请输入图片链接')
    return
  }
  
  const imageMarkdown = `![${imageForm.alt || '图片'}](${imageForm.url})`
  insertText(imageMarkdown)
  showImageDialog.value = false
  imageForm.url = ''
  imageForm.alt = ''
}

// 插入表格
const insertTable = () => {
  const { rows, cols } = tableForm
  let table = '\n'
  
  // 表头
  table += '|'
  for (let i = 0; i < cols; i++) {
    table += ` 列${i + 1} |`
  }
  table += '\n'
  
  // 分隔线
  table += '|'
  for (let i = 0; i < cols; i++) {
    table += ' --- |'
  }
  table += '\n'
  
  // 数据行
  for (let i = 0; i < rows - 1; i++) {
    table += '|'
    for (let j = 0; j < cols; j++) {
      table += '  |'
    }
    table += '\n'
  }
  
  insertText(table)
  showTableDialog.value = false
}

// 处理命令
const handleCommand = (command) => {
  switch (command) {
    case 'export':
      ElMessage.info('导出功能开发中...')
      break
    case 'share':
      ElMessage.info('分享功能开发中...')
      break
    case 'template':
      ElMessage.info('模板功能开发中...')
      break
  }
}

// 返回
const goBack = () => {
  router.push('/note')
}

// 页面加载
onMounted(async () => {
  await Promise.all([
    loadCategories(),
    loadTags(),
    loadNoteDetail()
  ])
})
</script>

<style lang="scss" scoped>
.note-editor-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.editor-header {
  background: white;
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
    
    .title-input {
      max-width: 400px;
      
      :deep(.el-input__wrapper) {
        box-shadow: none;
        border-bottom: 1px solid #dcdfe6;
        border-radius: 0;
      }
    }
  }
  
  .header-right {
    display: flex;
    gap: 8px;
  }
}

.editor-toolbar {
  background: white;
  padding: 8px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .toolbar-left {
    display: flex;
    gap: 12px;
  }
}

.editor-body {
  flex: 1;
  display: flex;
  overflow: hidden;
  
  &.split-mode {
    .editor-panel,
    .preview-panel {
      width: 50%;
    }
  }
  
  .editor-panel {
    width: 100%;
    background: white;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #ebeef5;
    
    .editor-tools {
      padding: 8px 16px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
    
    .editor-textarea {
      flex: 1;
      
      :deep(.el-textarea__inner) {
        height: 100%;
        border: none;
        border-radius: 0;
        resize: none;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 14px;
        line-height: 1.6;
        padding: 16px;
      }
    }
  }
  
  .preview-panel {
    width: 100%;
    background: white;
    overflow-y: auto;
    
    .preview-content {
      padding: 20px;
      line-height: 1.8;
      
      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin: 20px 0 10px 0;
        font-weight: 600;
      }
      
      :deep(p) {
        margin-bottom: 16px;
      }
      
      :deep(code) {
        background: #f1f1f1;
        padding: 2px 4px;
        border-radius: 3px;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      }
      
      :deep(blockquote) {
        border-left: 4px solid #ddd;
        padding-left: 16px;
        margin: 16px 0;
        color: #666;
      }
      
      :deep(li) {
        margin-bottom: 4px;
      }
    }
  }
}

.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 100%;
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
  
  :deep(.el-upload-dragger) {
    padding: 40px;
  }
}

@media (max-width: 768px) {
  .editor-header {
    flex-direction: column;
    gap: 12px;
    
    .header-left {
      width: 100%;
    }
  }
  
  .editor-toolbar {
    flex-direction: column;
    gap: 8px;
  }
  
  .editor-body.split-mode {
    flex-direction: column;
    
    .editor-panel,
    .preview-panel {
      width: 100%;
      height: 50%;
    }
  }
}
</style>
